import React, { useState, useEffect, useRef } from 'react';
import { Box, Typography, Card, CardContent, Grid, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, Button, TextField, Dialog, DialogTitle, DialogContent, DialogActions, FormControl, InputLabel, Select, MenuItem, Tabs, Tab, Divider, IconButton, Chip } from '@mui/material';
import { Map, DirectionsCar, CalendarToday, Clock, ChevronRight, Search, Refresh, FilterList, PlayArrow, Pause, Download, Info, AddAlert, BatteryFull, ArrowRight } from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';

const TrackHistory = () => {
  const [vehicleData, setVehicleData] = useState([]);
  const [selectedVehicle, setSelectedVehicle] = useState(null);
  const [trackData, setTrackData] = useState([]);
  const [currentLocation, setCurrentLocation] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [userData, setUserData] = useState(null);
  const [dateRange, setDateRange] = useState({ startDate: '', endDate: '' });
  const [playbackSpeed, setPlaybackSpeed] = useState(1);
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentPlaybackIndex, setCurrentPlaybackIndex] = useState(0);
  const [mapLoaded, setMapLoaded] = useState(false);
  const [fuelData, setFuelData] = useState([]);
  const [batteryData, setBatteryData] = useState([]);
  const mapRef = useRef(null);
  const playbackIntervalRef = useRef(null);
  const navigate = useNavigate();

  useEffect(() => {
    // 获取用户信息
    const savedUserInfo = localStorage.getItem('userInfo');
    if (savedUserInfo) {
      try {
        const userInfo = JSON.parse(savedUserInfo);
        setUserData(userInfo);
      } catch (error) {
        console.error('Failed to parse user info:', error);
      }
    }

    // 加载车辆数据
    const loadData = async () => {
      try {
        setLoading(true);
        
        // 在开发环境中使用模拟数据
        if (process.env.NODE_ENV === 'development') {
          // 从localStorage获取或创建模拟数据
          const storedVehicles = localStorage.getItem('vehicles');
          
          if (storedVehicles) {
            const vehicles = JSON.parse(storedVehicles);
            setVehicleData(vehicles);
            if (vehicles.length > 0 && !selectedVehicle) {
              setSelectedVehicle(vehicles[0]);
              loadVehicleTrackData(vehicles[0].id);
            }
          } else {
            // 如果没有存储的车辆数据，创建一些模拟数据
            const mockVehicles = [
              {
                id: 'vehicle1',
                licensePlate: '京A12345',
                type: '小轿车',
                brand: '特斯拉',
                model: 'Model 3',
                status: 'online',
                lastUpdated: '2024-05-16T14:30:00Z',
                location: { lat: 39.9042, lng: 116.4074 }
              },
              {
                id: 'vehicle2',
                licensePlate: '京B54321',
                type: '货车',
                brand: '福田',
                model: '欧曼',
                status: 'online',
                lastUpdated: '2024-05-16T14:25:00Z',
                location: { lat: 39.9142, lng: 116.4174 }
              }
            ];
            setVehicleData(mockVehicles);
            setSelectedVehicle(mockVehicles[0]);
            loadVehicleTrackData(mockVehicles[0].id);
            localStorage.setItem('vehicles', JSON.stringify(mockVehicles));
          }
        }
        
        setError(null);
      } catch (err) {
        console.error('Failed to load vehicles:', err);
        setError('Failed to load vehicles. Please try again later.');
      } finally {
        setLoading(false);
      }
    };

    loadData();
  }, [selectedVehicle]);

  // 模拟加载地图SDK
  useEffect(() => {
    // 实际项目中这里应该加载真实的地图SDK
    const timer = setTimeout(() => {
      setMapLoaded(true);
    }, 1000);

    return () => clearTimeout(timer);
  }, []);

  // 加载车辆轨迹数据
  const loadVehicleTrackData = (vehicleId) => {
    try {
      // 在开发环境中使用模拟数据
      if (process.env.NODE_ENV === 'development') {
        const storedTracks = localStorage.getItem(`vehicle_${vehicleId}_tracks`);
        
        if (storedTracks) {
          const tracks = JSON.parse(storedTracks);
          setTrackData(tracks);
          setCurrentLocation(tracks[tracks.length - 1] || null);
          loadFuelAndBatteryData(vehicleId);
        } else {
          // 创建模拟轨迹数据
          const mockTracks = generateMockTrackData();
          setTrackData(mockTracks);
          setCurrentLocation(mockTracks[mockTracks.length - 1] || null);
          localStorage.setItem(`vehicle_${vehicleId}_tracks`, JSON.stringify(mockTracks));
          loadFuelAndBatteryData(vehicleId);
        }
      }
    } catch (error) {
      console.error('Failed to load track data:', error);
    }
  };

  // 加载油量和电量数据
  const loadFuelAndBatteryData = (vehicleId) => {
    try {
      const storedFuelData = localStorage.getItem(`vehicle_${vehicleId}_fuel`);
      const storedBatteryData = localStorage.getItem(`vehicle_${vehicleId}_battery`);
      
      if (storedFuelData) {
        setFuelData(JSON.parse(storedFuelData));
      } else {
        const mockFuelData = generateMockFuelData();
        setFuelData(mockFuelData);
        localStorage.setItem(`vehicle_${vehicleId}_fuel`, JSON.stringify(mockFuelData));
      }
      
      if (storedBatteryData) {
        setBatteryData(JSON.parse(storedBatteryData));
      } else {
        const mockBatteryData = generateMockBatteryData();
        setBatteryData(mockBatteryData);
        localStorage.setItem(`vehicle_${vehicleId}_battery`, JSON.stringify(mockBatteryData));
      }
    } catch (error) {
      console.error('Failed to load fuel and battery data:', error);
    }
  };

  // 生成模拟轨迹数据
  const generateMockTrackData = () => {
    const tracks = [];
    const baseLat = 39.9042;
    const baseLng = 116.4074;
    
    for (let i = 0; i < 100; i++) {
      const timestamp = new Date();
      timestamp.setMinutes(timestamp.getMinutes() - (100 - i) * 5);
      
      tracks.push({
        id: `track_${i}`,
        timestamp: timestamp.toISOString(),
        location: {
          lat: baseLat + (Math.random() - 0.5) * 0.05,
          lng: baseLng + (Math.random() - 0.5) * 0.05
        },
        speed: Math.floor(Math.random() * 80) + 20, // 20-100 km/h
        direction: Math.floor(Math.random() * 360),
        fuelLevel: Math.floor(Math.random() * 30) + 70, // 70-100%
        batteryLevel: Math.floor(Math.random() * 20) + 80, // 80-100%
        status: 'normal'
      });
    }
    
    return tracks;
  };

  // 生成模拟油量数据
  const generateMockFuelData = () => {
    const fuelData = [];
    
    for (let i = 0; i < 24; i++) {
      const timestamp = new Date();
      timestamp.setHours(timestamp.getHours() - (24 - i));
      
      fuelData.push({
        timestamp: timestamp.toISOString(),
        level: Math.floor(Math.random() * 20) + 80 // 80-100%
      });
    }
    
    return fuelData;
  };

  // 生成模拟电量数据
  const generateMockBatteryData = () => {
    const batteryData = [];
    
    for (let i = 0; i < 24; i++) {
      const timestamp = new Date();
      timestamp.setHours(timestamp.getHours() - (24 - i));
      
      batteryData.push({
        timestamp: timestamp.toISOString(),
        level: Math.floor(Math.random() * 15) + 85 // 85-100%
      });
    }
    
    return batteryData;
  };

  // 处理车辆选择变化
  const handleVehicleChange = (event) => {
    const vehicleId = event.target.value;
    const vehicle = vehicleData.find(v => v.id === vehicleId);
    setSelectedVehicle(vehicle);
    setTrackData([]);
    setCurrentLocation(null);
    setFuelData([]);
    setBatteryData([]);
    loadVehicleTrackData(vehicleId);
  };

  // 处理日期范围变化
  const handleDateRangeChange = (field, value) => {
    setDateRange(prev => ({ ...prev, [field]: value }));
  };

  // 搜索轨迹数据
  const handleSearchTracks = () => {
    // 实际项目中这里应该根据日期范围过滤轨迹数据
    // 在开发环境中我们简单地重新加载数据
    if (selectedVehicle) {
      loadVehicleTrackData(selectedVehicle.id);
    }
  };

  // 开始/暂停回放
  const togglePlayback = () => {
    if (isPlaying) {
      // 暂停回放
      if (playbackIntervalRef.current) {
        clearInterval(playbackIntervalRef.current);
        playbackIntervalRef.current = null;
      }
    } else {
      // 开始回放
      playbackIntervalRef.current = setInterval(() => {
        setCurrentPlaybackIndex(prev => {
          if (prev >= trackData.length - 1) {
            // 回放结束
            clearInterval(playbackIntervalRef.current);
            playbackIntervalRef.current = null;
            setIsPlaying(false);
            return prev;
          }
          return prev + 1;
        });
      }, 1000 / playbackSpeed);
    }
    setIsPlaying(!isPlaying);
  };

  // 重置回放
  const resetPlayback = () => {
    if (playbackIntervalRef.current) {
      clearInterval(playbackIntervalRef.current);
      playbackIntervalRef.current = null;
    }
    setIsPlaying(false);
    setCurrentPlaybackIndex(0);
  };

  // 格式化时间戳
  const formatTimestamp = (timestamp) => {
    const date = new Date(timestamp);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  };

  // 获取状态样式
  const getStatusStyle = (status) => {
    switch (status) {
      case 'online':
        return { color: 'success.main' };
      case 'offline':
        return { color: 'error.main' };
      case 'warning':
        return { color: 'warning.main' };
      default:
        return { color: 'text.primary' };
    }
  };

  // 获取状态文本
  const getStatusText = (status) => {
    switch (status) {
      case 'online':
        return '在线';
      case 'offline':
        return '离线';
      case 'warning':
        return '警告';
      default:
        return status;
    }
  };

  return (
    <Box sx={{ p: 3 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 2 }}>
        <Typography variant="h4" component="h1" gutterBottom>
          <span style={{ display: 'flex', alignItems: 'center' }}>
            <Map sx={{ mr: 2 }} />
            行迹回顾
          </span>
        </Typography>
      </div>
      
      {loading && (
        <Typography variant="body1">加载数据中...</Typography>
      )}
      
      {error && (
        <div style={{ color: 'error.main', marginBottom: 2 }}>{error}</div>
      )}
      
      {!loading && (
        <>
          {/* 车辆选择和搜索区域 */}
          <Card sx={{ mb: 4 }}>
            <CardContent>
              <Grid container spacing={3}>
                <Grid item xs={12} sm={6} md={4}>
                  <FormControl fullWidth>
                    <InputLabel>选择车辆</InputLabel>
                    <Select
                      value={selectedVehicle?.id || ''}
                      onChange={handleVehicleChange}
                      label="选择车辆"
                    >
                      {vehicleData.map(vehicle => (
                        <MenuItem key={vehicle.id} value={vehicle.id}>
                          {vehicle.licensePlate} ({vehicle.brand} {vehicle.model})
                        </MenuItem>
                      ))}
                    </Select>
                  </FormControl>
                </Grid>
                <Grid item xs={12} sm={6} md={4}>
                  <TextField
                    fullWidth
                    label="开始日期"
                    type="datetime-local"
                    value={dateRange.startDate}
                    onChange={(e) => handleDateRangeChange('startDate', e.target.value)}
                    InputLabelProps={{ shrink: true }}
                  />
                </Grid>
                <Grid item xs={12} sm={6} md={4}>
                  <TextField
                    fullWidth
                    label="结束日期"
                    type="datetime-local"
                    value={dateRange.endDate}
                    onChange={(e) => handleDateRangeChange('endDate', e.target.value)}
                    InputLabelProps={{ shrink: true }}
                  />
                </Grid>
                <Grid item xs={12} sm={6} md={4} style={{ display: 'flex', gap: 1, alignItems: 'flex-end' }}>
                  <Button 
                    variant="contained" 
                    color="primary" 
                    startIcon={<Search />}
                    onClick={handleSearchTracks}
                    fullWidth
                  >
                    搜索轨迹
                  </Button>
                  <Button 
                    variant="outlined" 
                    startIcon={<Refresh />}
                    onClick={handleSearchTracks}
                    fullWidth
                  >
                    刷新
                  </Button>
                </Grid>
              </Grid>
            </CardContent>
          </Card>
          
          {selectedVehicle && (
            <>
              {/* 车辆信息卡片 */}
              <Card sx={{ mb: 4 }}>
                <CardContent>
                  <Grid container spacing={3}>
                    <Grid item xs={12} sm={6} md={3}>
                      <Typography variant="subtitle2" color="text.secondary">车牌号</Typography>
                      <Typography variant="h6">{selectedVehicle.licensePlate}</Typography>
                    </Grid>
                    <Grid item xs={12} sm={6} md={3}>
                      <Typography variant="subtitle2" color="text.secondary">车辆型号</Typography>
                      <Typography variant="h6">{selectedVehicle.brand} {selectedVehicle.model}</Typography>
                    </Grid>
                    <Grid item xs={12} sm={6} md={3}>
                      <Typography variant="subtitle2" color="text.secondary">状态</Typography>
                      <Typography variant="h6" sx={getStatusStyle(selectedVehicle.status)}>
                        {getStatusText(selectedVehicle.status)}
                      </Typography>
                    </Grid>
                    <Grid item xs={12} sm={6} md={3}>
                      <Typography variant="subtitle2" color="text.secondary">最后更新时间</Typography>
                      <Typography variant="h6">{formatTimestamp(selectedVehicle.lastUpdated)}</Typography>
                    </Grid>
                  </Grid>
                </CardContent>
              </Card>
              
              {/* 地图和轨迹回放区域 */}
              <Grid container spacing={3}>
                {/* 地图区域 */}
                <Grid item xs={12} md={8}>
                  <Card>
                    <CardContent>
                      <Typography variant="h6" gutterBottom>
                        车辆轨迹地图
                      </Typography>
                      {/* 模拟地图显示 */}
                      <div style={{ 
                        height: 400, 
                        width: '100%', 
                        backgroundColor: '#f0f0f0', 
                        position: 'relative',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        overflow: 'hidden'
                      }}>
                        {mapLoaded && (
                          <>
                            {/* 模拟地图背景 */}
                            <div style={{ 
                              position: 'absolute', 
                              top: 0, 
                              left: 0, 
                              width: '100%', 
                              height: '100%',
                              backgroundImage: `url('data:image/svg+xml,%3Csvg width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"%3E%3Cpath d="M11 18c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm48 25c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm-43-7c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm63 31c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM34 90c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm56-76c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM12 86c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm28-65c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm23-11c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-6 60c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm29 22c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zM32 63c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm57-13c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-9-21c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM60 91c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM35 41c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM12 60c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2z" fill='%239C92AC' fill-opacity='0.1' fill-rule='evenodd'/%3E%3C/svg%3E')`,
                            }}></div>
                            
                            {/* 模拟轨迹线 */}
                            {trackData.length > 0 && (
                              <svg style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }}>
                                <polyline
                                  points={trackData.map(point => 
                                    `${(point.location.lng - 116.4) * 10000},${(39.91 - point.location.lat) * 10000}`
                                  ).join(' ')}
                                  fill="none"
                                  stroke="#3f51b5"
                                  strokeWidth="2"
                                />
                              </svg>
                            )}
                            
                            {/* 模拟车辆位置 */}
                            {trackData.length > 0 && (
                              <div 
                                style={{
                                  position: 'absolute',
                                  top: `${(39.91 - trackData[currentPlaybackIndex].location.lat) * 10000}px`,
                                  left: `${(trackData[currentPlaybackIndex].location.lng - 116.4) * 10000}px`,
                                  transform: 'translate(-50%, -50%)',
                                  zIndex: 10
                                }}
                              >
                                <DirectionsCar size={24} color="primary" />
                              </div>
                            )}
                          </>)}
                      </div>
                    </CardContent>
                  </Card>
                </Grid>
                
                {/* 回放控制和数据区域 */}
                <Grid item xs={12} md={4}>
                  <Card>
                    <CardContent>
                      <Typography variant="h6" gutterBottom>
                        轨迹回放控制
                      </Typography>
                      
                      {/* 回放控制按钮 */}
                      <div style={{ display: 'flex', justifyContent: 'center', gap: 16, marginBottom: 24 }}>
                        <Button 
                          variant="outlined" 
                          color="primary"
                          onClick={resetPlayback}
                          startIcon={<Refresh />}
                        >
                          重置
                        </Button>
                        <Button 
                          variant="contained" 
                          color="primary"
                          onClick={togglePlayback}
                          startIcon={isPlaying ? <Pause /> : <PlayArrow />}
                        >
                          {isPlaying ? '暂停' : '播放'}
                        </Button>
                        <Button 
                          variant="outlined" 
                          color="primary"
                          startIcon={<Download />}
                        >
                          导出
                        </Button>
                      </div>
                      
                      {/* 回放速度控制 */}
                      <div style={{ marginBottom: 24 }}>
                        <Typography variant="subtitle2" gutterBottom>回放速度</Typography>
                        <FormControl fullWidth>
                          <InputLabel>速度倍率</InputLabel>
                          <Select
                            value={playbackSpeed}
                            onChange={(e) => setPlaybackSpeed(e.target.value)}
                            label="速度倍率"
                          >
                            <MenuItem value={0.5}>0.5x</MenuItem>
                            <MenuItem value={1}>1x</MenuItem>
                            <MenuItem value={2}>2x</MenuItem>
                            <MenuItem value={4}>4x</MenuItem>
                            <MenuItem value={8}>8x</MenuItem>
                          </Select>
                        </FormControl>
                      </div>
                      
                      {/* 当前播放状态 */}
                      {trackData.length > 0 && (
                        <Card variant="outlined" sx={{ p: 2, mb: 2 }}>
                          <Typography variant="subtitle2" color="text.secondary">当前位置</Typography>
                          <Typography variant="body1">
                            时间: {formatTimestamp(trackData[currentPlaybackIndex].timestamp)}
                          </Typography>
                          <Typography variant="body1">
                            坐标: {trackData[currentPlaybackIndex].location.lat.toFixed(6)}, 
                            {trackData[currentPlaybackIndex].location.lng.toFixed(6)}
                          </Typography>
                          <Typography variant="body1">
                            速度: {trackData[currentPlaybackIndex].speed} km/h
                          </Typography>
                        </Card>
                      )}
                    </CardContent>
                  </Card>
                </Grid>
              </Grid>
              
              {/* 油电数据图表 */}
              <Card sx={{ mt: 4 }}>
                <CardContent>
                  <Typography variant="h6" gutterBottom>
                    油电数据监控
                  </Typography>
                  <Tabs value={0} centered>
                    <Tab label="油量监控" />
                    <Tab label="电量监控" />
                  </Tabs>
                  <Divider sx={{ mb: 2 }} />
                  
                  {/* 模拟油量图表 */}
                  <div style={{ height: 200, width: '100%', position: 'relative' }}>
                    {/* 模拟油量曲线 */}
                    {fuelData.length > 0 && (
                      <svg style={{ width: '100%', height: '100%' }}>
                        <polyline
                          points={fuelData.map((point, index) => 
                            `${(index / (fuelData.length - 1)) * 100}%,${(100 - point.level) * 2}`
                          ).join(' ')}
                          fill="none"
                          stroke="#ff5722"
                          strokeWidth="2"
                        />
                        {/* Y轴标签 */}
                        <text x="10" y="20" fontSize="12">100%</text>
                        <text x="10" y="200" fontSize="12">0%</text>
                        {/* X轴标签 */}
                        <text x="10" y="220" fontSize="12">24小时前</text>
                        <text x="95%" y="220" fontSize="12">现在</text>
                      </svg>
                    )}
                    
                    {/* 当前油量指示器 */}
                    {fuelData.length > 0 && (
                      <div style={{ position: 'absolute', top: 10, right: 10, display: 'flex', alignItems: 'center', gap: 8 }}>
                        <AddAlert color="warning" />
                        <Typography variant="body1">
                          当前油量: {fuelData[fuelData.length - 1].level}%
                        </Typography>
                      </div>
                    )}
                    
                    {/* 当前电量指示器 */}
                    {batteryData.length > 0 && (
                      <div style={{ position: 'absolute', top: 40, right: 10, display: 'flex', alignItems: 'center', gap: 8 }}>
                        <BatteryFull color="success" />
                        <Typography variant="body1">
                          当前电量: {batteryData[batteryData.length - 1].level}%
                        </Typography>
                      </div>
                    )}
                  </div>
                </CardContent>
              </Card>
            </>
          )}
        </>
      )}
    </Box>
  );
};

export default TrackHistory;